#ifndef PYTHON_BIND_SERVER_H
#define PYTHON_BIND_SERVER_H

#include "../server/IPythonBindServer.h"
#include <QObject>
#include <QSharedPointer>
#include <QString>
#include <map>
#include <memory>
#include <pybind11/embed.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

namespace pybind11 {
class object;
class args;
} // namespace pybind11

class ObjectRegistry;
class ScriptManager;
class PropertyAccessor;

class PythonBindServer : public IPythonBindServer {
public:
  // 构造函数和析构函数
  PythonBindServer();
  virtual ~PythonBindServer();

  // 初始化Python环境
  bool initialize() override;
  bool isInitialized() const override;

  // 对象注册与管理
  bool registerObject(QObject *obj, const QString &objectId = "",
                      const QString &scriptPath = "") override;
  bool unregisterObject(const QString &objectId) override;
  bool unregisterObject(QObject *obj) override;
  QObject *getObject(const QString &objectId) const override;
  QString getObjectId(QObject *obj) const override;

  // 脚本管理
  bool loadScript(const QString &objectId, const QString &scriptPath) override;
  bool unloadScript(const QString &objectId) override;
  bool reloadScript(const QString &objectId) override;

  // 属性访问接口
  pybind11::object getProperty(const QString &objectId,
                               const QString &propertyName) override;
  bool setProperty(const QString &objectId, const QString &propertyName,
                   const pybind11::object &value) override;

  // 脚本函数执行
  pybind11::object
  executeFunction(const QString &objectId, const QString &functionName,
                  const pybind11::args &args = pybind11::tuple()) override;

  // 新增的重载方法，不带args参数
  pybind11::object executeFunction(const QString &objectId,
                                   const QString &functionName) override;

  // 对象间交互
  pybind11::object getObjectReference(const QString &objectId) override;

private:
  // 禁止拷贝
  PythonBindServer(const PythonBindServer &) = delete;
  PythonBindServer &operator=(const PythonBindServer &) = delete;

  // 内部辅助方法
  QString generateObjectId(QObject *obj);
  bool isValidObjectId(const QString &objectId) const;

  // 成员变量
  std::unique_ptr<pybind11::scoped_interpreter> m_interpreter;
  std::unique_ptr<ObjectRegistry> m_objectRegistry;
  std::unique_ptr<ScriptManager> m_scriptManager;
  std::unique_ptr<PropertyAccessor> m_propertyAccessor;
  bool m_initialized;

  // 声明友元以允许unique_ptr访问私有析构函数
  friend struct std::default_delete<PythonBindServer>;
};

#endif // PYTHON_BIND_SERVER_H